// 简化的游戏增强系统 - 确保能正常工作的版本
(function() {
    'use strict';
    
    console.log('🎮 简化增强系统开始加载...');
    
    // 简单的增强管理器
    class SimpleEnhancements {
        constructor() {
            this.initialized = false;
            this.systems = {};
        }
        
        initialize() {
            if (this.initialized) return;
            
            console.log('🚀 开始初始化简化增强系统');
            
            try {
                // 等待游戏完全加载
                this.waitForGame(() => {
                    this.setupBasicEnhancements();
                    this.initialized = true;
                    console.log('✅ 简化增强系统初始化完成');
                });
                
            } catch (error) {
                console.error('❌ 简化增强系统初始化失败:', error);
            }
        }
        
        waitForGame(callback) {
            let attempts = 0;
            const maxAttempts = 20;
            
            const checkGame = () => {
                attempts++;
                
                if (window.gameEngine && window.player && window.levelManager) {
                    console.log('✅ 游戏系统检测完成');
                    callback();
                } else if (attempts < maxAttempts) {
                    console.log(`⏳ 等待游戏加载... (${attempts}/${maxAttempts})`);
                    setTimeout(checkGame, 1000);
                } else {
                    console.error('❌ 游戏系统加载超时');
                }
            };
            
            checkGame();
        }
        
        setupBasicEnhancements() {
            // 1. 闪避系统 (最简单的)
            this.setupDodgeSystem();
            
            // 2. 可破坏环境
            this.setupEnvironment();
            
            // 3. 连击系统
            this.setupComboSystem();
            
            // 4. 视觉增强
            this.setupVisualEffects();
            
            // 启动更新循环
            this.startUpdateLoop();
        }
        
        // 1. 闪避系统
        setupDodgeSystem() {
            console.log('🏃 设置闪避系统...');
            
            this.systems.dodge = {
                active: false,
                cooldown: 0,
                cooldownTime: 1000
            };
            
            // 空格键闪避
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space' && this.systems.dodge.cooldown <= 0) {
                    e.preventDefault();
                    this.performDodge();
                }
            });
            
            console.log('✅ 闪避系统设置完成 - 按空格键闪避');
        }
        
        performDodge() {
            if (!window.player || this.systems.dodge.active) return;
            
            console.log('🏃 执行闪避');
            
            this.systems.dodge.active = true;
            this.systems.dodge.cooldown = this.systems.dodge.cooldownTime;
            
            // 短暂无敌
            window.player.invulnerable = true;
            
            // 视觉效果
            this.createDodgeEffect();
            
            // 结束闪避
            setTimeout(() => {
                this.systems.dodge.active = false;
                if (window.player) {
                    window.player.invulnerable = false;
                }
            }, 300);
        }
        
        createDodgeEffect() {
            if (!window.player || !window.gameEngine) return;
            
            // 创建白色粒子效果
            for (let i = 0; i < 8; i++) {
                window.gameEngine.particles.push({
                    x: window.player.x + (Math.random() - 0.5) * 20,
                    y: window.player.y + (Math.random() - 0.5) * 20,
                    vx: (Math.random() - 0.5) * 100,
                    vy: (Math.random() - 0.5) * 100,
                    life: 0.5,
                    maxLife: 0.5,
                    color: '#FFFFFF',
                    size: Math.random() * 4 + 2
                });
            }
        }
        
        // 2. 可破坏环境
        setupEnvironment() {
            console.log('🌍 设置环境系统...');
            
            this.systems.environment = {
                objects: [],
                initialized: false
            };
            
            // 创建可破坏物品
            this.createEnvironmentObjects();
            
            console.log('✅ 环境系统设置完成');
        }
        
        createEnvironmentObjects() {
            if (!window.levelManager) return;
            
            console.log('🪑 创建可破坏物品...');
            
            this.systems.environment.objects = [];
            
            // 创建一些桌子
            for (let i = 0; i < 5; i++) {
                this.systems.environment.objects.push({
                    x: Math.random() * 800 + 100,
                    y: Math.random() * 600 + 100,
                    width: 40,
                    height: 30,
                    health: 2,
                    maxHealth: 2,
                    type: 'table',
                    destroyed: false
                });
            }
            
            // 创建爆炸桶
            for (let i = 0; i < 2; i++) {
                this.systems.environment.objects.push({
                    x: Math.random() * 700 + 150,
                    y: Math.random() * 500 + 150,
                    width: 25,
                    height: 35,
                    health: 1,
                    type: 'barrel',
                    destroyed: false,
                    explosive: true
                });
            }
            
            this.systems.environment.initialized = true;
            console.log(`✅ 创建了 ${this.systems.environment.objects.length} 个环境物品`);
        }
        
        // 3. 连击系统
        setupComboSystem() {
            console.log('🔥 设置连击系统...');
            
            this.systems.combo = {
                count: 0,
                lastKillTime: 0,
                timeout: 3000
            };
            
            console.log('✅ 连击系统设置完成');
        }
        
        addKill() {
            const now = Date.now();
            
            if (now - this.systems.combo.lastKillTime > this.systems.combo.timeout) {
                this.systems.combo.count = 1;
            } else {
                this.systems.combo.count++;
            }
            
            this.systems.combo.lastKillTime = now;
            
            // 显示连击
            this.showCombo();
            
            // 连击奖励
            if (this.systems.combo.count % 5 === 0) {
                this.giveComboReward();
            }
            
            console.log(`🔥 连击: ${this.systems.combo.count}x`);
        }
        
        showCombo() {
            if (!window.player || !window.gameEngine) return;
            
            let color = '#FFFFFF';
            if (this.systems.combo.count >= 10) color = '#FFD700';
            else if (this.systems.combo.count >= 5) color = '#00FF00';
            
            // 添加浮动文字
            window.gameEngine.floatingTexts.push({
                x: window.player.x,
                y: window.player.y - 30,
                text: `${this.systems.combo.count}x`,
                color: color,
                life: 1.5,
                maxLife: 1.5,
                vy: -30,
                size: 16
            });
        }
        
        giveComboReward() {
            if (!window.player) return;
            
            // 生命值奖励
            if (window.player.health < window.player.maxHealth) {
                window.player.health = Math.min(window.player.maxHealth, window.player.health + 20);
                if (window.player.updateHealthUI) window.player.updateHealthUI();
                
                // 显示奖励
                window.gameEngine.floatingTexts.push({
                    x: window.player.x,
                    y: window.player.y,
                    text: '+20 HP',
                    color: '#00FF00',
                    life: 2,
                    maxLife: 2,
                    vy: -20,
                    size: 14
                });
            }
            
            console.log(`🏆 连击奖励: ${this.systems.combo.count}x`);
        }
        
        // 4. 视觉效果
        setupVisualEffects() {
            console.log('✨ 设置视觉效果...');
            
            this.systems.visual = {
                screenShake: 0,
                shakeTime: 0
            };
            
            console.log('✅ 视觉效果设置完成');
        }
        
        screenShake(intensity, duration = 200) {
            // 震动效果已禁用
            return;
        }
        
        // 更新循环
        startUpdateLoop() {
            console.log('🔄 启动更新循环...');
            
            setInterval(() => {
                this.updateSystems();
            }, 16); // ~60fps
        }
        
        updateSystems() {
            if (!this.initialized) return;
            
            try {
                this.updateDodgeSystem();
                this.updateEnvironment();
                this.updateComboSystem();
                this.updateVisualEffects();
                this.updateZombieKillDetection();
            } catch (error) {
                // 静默处理错误，不影响游戏运行
            }
        }
        
        updateDodgeSystem() {
            if (this.systems.dodge.cooldown > 0) {
                this.systems.dodge.cooldown -= 16;
            }
        }
        
        updateEnvironment() {
            if (!window.gameEngine || !this.systems.environment.initialized) return;
            
            // 检查子弹与环境物品的碰撞
            window.gameEngine.bullets.forEach((bullet, bulletIndex) => {
                this.systems.environment.objects.forEach((obj, objIndex) => {
                    if (!obj.destroyed && this.isColliding(bullet, obj)) {
                        // 移除子弹
                        window.gameEngine.bullets.splice(bulletIndex, 1);
                        
                        // 伤害物品
                        obj.health--;
                        
                        if (obj.health <= 0) {
                            obj.destroyed = true;
                            
                            if (obj.explosive) {
                                this.explodeBarrel(obj);
                            } else {
                                this.createDebris(obj);
                            }
                        }
                    }
                });
            });
        }
        
        explodeBarrel(barrel) {
            console.log('💥 爆炸桶爆炸！');
            
            // 屏幕震动
            // this.screenShake(15); // 禁用震动效果
            
            // 爆炸粒子
            for (let i = 0; i < 15; i++) {
                const angle = (Math.PI * 2 * i) / 15;
                const speed = Math.random() * 200 + 100;
                
                window.gameEngine.particles.push({
                    x: barrel.x,
                    y: barrel.y,
                    vx: Math.cos(angle) * speed,
                    vy: Math.sin(angle) * speed,
                    life: Math.random() * 1 + 0.5,
                    maxLife: Math.random() * 1 + 0.5,
                    color: ['#FF4500', '#FF6347', '#FFD700'][Math.floor(Math.random() * 3)],
                    size: Math.random() * 6 + 3
                });
            }
            
            // 伤害范围内的僵尸
            const explosionRadius = 80;
            window.gameEngine.zombies.forEach(zombie => {
                const distance = this.getDistance(zombie, barrel);
                if (distance < explosionRadius) {
                    const damage = Math.floor(40 * (1 - distance / explosionRadius));
                    zombie.health -= damage;
                    
                    if (zombie.health <= 0) {
                        this.addKill();
                    }
                }
            });
        }
        
        createDebris(obj) {
            // 碎片效果
            for (let i = 0; i < 6; i++) {
                window.gameEngine.particles.push({
                    x: obj.x + Math.random() * obj.width,
                    y: obj.y + Math.random() * obj.height,
                    vx: (Math.random() - 0.5) * 150,
                    vy: (Math.random() - 0.5) * 150,
                    life: 1.5,
                    maxLife: 1.5,
                    color: '#8B4513',
                    size: Math.random() * 3 + 2
                });
            }
        }
        
        updateComboSystem() {
            const now = Date.now();
            if (this.systems.combo.count > 0 && 
                now - this.systems.combo.lastKillTime > this.systems.combo.timeout) {
                this.systems.combo.count = 0;
            }
        }
        
        updateVisualEffects() {
            if (this.systems.visual.shakeTime > 0) {
                this.systems.visual.shakeTime -= 16;
                if (this.systems.visual.shakeTime <= 0) {
                    this.systems.visual.screenShake = 0;
                }
            }
        }
        
        updateZombieKillDetection() {
            // 简单的击杀检测
            if (!this.lastZombieCount) {
                this.lastZombieCount = window.gameEngine?.zombies?.length || 0;
                return;
            }
            
            const currentZombieCount = window.gameEngine?.zombies?.length || 0;
            if (currentZombieCount < this.lastZombieCount) {
                const kills = this.lastZombieCount - currentZombieCount;
                for (let i = 0; i < kills; i++) {
                    this.addKill();
                }
            }
            
            this.lastZombieCount = currentZombieCount;
        }
        
        // 工具函数
        isColliding(obj1, obj2) {
            const o1 = {
                x: obj1.x - (obj1.radius || obj1.width/2 || 0),
                y: obj1.y - (obj1.radius || obj1.height/2 || 0),
                width: obj1.radius * 2 || obj1.width || 10,
                height: obj1.radius * 2 || obj1.height || 10
            };
            
            return o1.x < obj2.x + obj2.width &&
                   o1.x + o1.width > obj2.x &&
                   o1.y < obj2.y + obj2.height &&
                   o1.y + o1.height > obj2.y;
        }
        
        getDistance(obj1, obj2) {
            const dx = obj1.x - obj2.x;
            const dy = obj1.y - obj2.y;
            return Math.sqrt(dx * dx + dy * dy);
        }
        
        // 自定义渲染
        renderEnvironment(ctx) {
            if (!this.systems.environment.initialized) return;
            
            this.systems.environment.objects.forEach(obj => {
                if (obj.destroyed) return;
                
                ctx.save();
                
                if (obj.type === 'table') {
                    ctx.fillStyle = '#8B4513';
                    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
                    
                    if (obj.health < obj.maxHealth) {
                        ctx.fillStyle = '#654321';
                        ctx.fillRect(obj.x + 2, obj.y + 2, obj.width - 4, obj.height - 4);
                    }
                } else if (obj.type === 'barrel') {
                    ctx.fillStyle = '#DC143C';
                    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
                    ctx.fillStyle = '#FF6347';
                    ctx.fillRect(obj.x + 3, obj.y + 3, obj.width - 6, obj.height - 6);
                }
                
                ctx.restore();
            });
        }
        
        renderUI(ctx) {
            // 渲染连击信息
            if (this.systems.combo.count > 0) {
                ctx.save();
                ctx.fillStyle = '#FFFFFF';
                ctx.font = 'bold 24px monospace';
                ctx.textAlign = 'center';
                ctx.fillText(`${this.systems.combo.count}x 连击`, 500, 50);
                ctx.restore();
            }
            
            // 渲染闪避状态
            if (this.systems.dodge.cooldown > 0) {
                ctx.save();
                ctx.fillStyle = '#FF6B6B';
                ctx.font = '14px monospace';
                ctx.textAlign = 'right';
                ctx.fillText(`闪避冷却: ${(this.systems.dodge.cooldown / 1000).toFixed(1)}s`, 980, 30);
                ctx.restore();
            } else {
                ctx.save();
                ctx.fillStyle = '#4ECDC4';
                ctx.font = '14px monospace';
                ctx.textAlign = 'right';
                ctx.fillText('闪避准备就绪 [空格]', 980, 30);
                ctx.restore();
            }
        }
        
        // 应用屏幕震动
        applyScreenShake(ctx) {
            if (this.systems.visual.screenShake > 0) {
                const intensity = this.systems.visual.screenShake * (this.systems.visual.shakeTime / 200);
                const offsetX = (Math.random() - 0.5) * intensity;
                const offsetY = (Math.random() - 0.5) * intensity;
                ctx.translate(offsetX, offsetY);
            }
        }
    }
    
    // 立即创建并初始化
    const simpleEnhancements = new SimpleEnhancements();
    window.simpleEnhancements = simpleEnhancements;
    
    // 等待页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => simpleEnhancements.initialize(), 3000);
        });
    } else {
        setTimeout(() => simpleEnhancements.initialize(), 3000);
    }
    
    // 集成到游戏渲染 - 更安全的方式
    const originalRender = window.GameEngine?.prototype?.render;
    if (originalRender) {
        window.GameEngine.prototype.render = function() {
            originalRender.call(this);
            
            if (window.simpleEnhancements?.initialized) {
                this.ctx.save();
                window.simpleEnhancements.applyScreenShake(this.ctx);
                window.simpleEnhancements.renderEnvironment(this.ctx);
                this.ctx.restore();
                
                window.simpleEnhancements.renderUI(this.ctx);
            }
        };
    }
    
    console.log('🎮 简化增强系统文件加载完成');
    
})();